package 力扣._98_验证BST;

import 力扣.公用数据结构.TreeNode;

public class Solution {

    boolean isAVL = true;

    int max(TreeNode root) { //当前子树最大值
        if (root.left == null && root.right == null)
            return root.val;
        else if (root.left != null && root.right == null)
            return Math.max(root.val, max(root.left));
        else if (root.left == null)
            return Math.max(root.val, max(root.right));
        else
            return Math.max(Math.max(root.val, max(root.right)), max(root.left));
    }

    //当前子树最小值
    int min(TreeNode root) { //当前子树最小值
        if (root.left == null && root.right == null)
            return root.val;
        else if (root.left != null && root.right == null)
            return Math.min(root.val, min(root.left));
        else if (root.left == null)
            return Math.min(root.val, min(root.right));
        else
            return Math.min(Math.min(root.val, min(root.right)), min(root.left));
    }

    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        if (root.left != null && root.right != null) {
            if (max(root.left) < root.val && root.val < min(root.right))
                return isValidBST(root.left)&&isValidBST(root.right);
            else
                return false;
        }else if (root.left == null && root.right != null) {
            if (root.val < min(root.right))
                return isValidBST(root.right);
            else
                return false;
        }else if (root.left != null) {
            if (max(root.left) < root.val)
                return isValidBST(root.left);
            else
                return false;
        }
        return true;
    }
}
